package com.Xht.www.servlet;

//后端响应查询用户历史订单信息的请求

import com.Xht.www.dao.UserHistoryOrdersDAO;
import com.Xht.www.po.UserHistoryOrdersPO;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/getUserHistoryOrders")
public class GetUserHistoryOrdersServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 获取用户 ID
        String userIdParam = request.getParameter("userId");
        if (userIdParam == null || userIdParam.isEmpty()) {
            out.println("{\"error\": \"用户 ID 不能为空\"}");
            return;
        }
        int userId = Integer.parseInt(userIdParam);

        // 查询用户历史订单
        UserHistoryOrdersDAO dao = new UserHistoryOrdersDAO();
        List<UserHistoryOrdersPO> orders = dao.getAllOrdersByUserId(userId);

        // 将订单信息转换为 JSON 格式输出
        StringBuilder json = new StringBuilder("[");
        for (int i = 0; i < orders.size(); i++) {
            UserHistoryOrdersPO order = orders.get(i);
            json.append("{");
            json.append("\"userId\": ").append(order.getUserId()).append(",");
            json.append("\"merchantName\": \"").append(order.getMerchantName()).append("\",");
            json.append("\"contactPhone\": \"").append(order.getContactPhone()).append("\",");
            json.append("\"totalConsumption\": ").append(order.getTotalConsumption()).append(",");
            json.append("\"bedType\": \"").append(order.getBedType()).append("\",");
            json.append("\"roomTypeQuantity\": ").append(order.getRoomTypeQuantity()).append(",");
            json.append("\"orderPlacementTime\": \"").append(order.getOrderPlacementTime()).append("\",");
            json.append("\"checkInTime\": \"").append(order.getCheckInTime()).append("\",");
            json.append("\"checkOutTime\": \"").append(order.getCheckOutTime()).append("\",");
            json.append("\"orderStatus\": \"").append(order.getOrderStatus()).append("\",");
            json.append("\"remarks\": \"").append(order.getRemarks()).append("\",");
            json.append("\"orderId\": ").append(order.getOrderId());
            json.append("}");
            if (i < orders.size() - 1) {
                json.append(",");
            }
        }
        json.append("]");

        out.println(json.toString());
    }
}